package com.tokenplus.thai.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.tokenplus.thai.R
import com.tokenplus.thai.base.BaseEditAction
import com.tokenplus.thai.base.BaseFormAction
import com.tokenplus.thai.databinding.ViewLoginUserNameInputBinding
import com.tokenplus.thai.extend.*

/**
<declare-styleable name="LoginUserNameInput">
<attr name="inputTitle" format="string" />
<attr name="inputTextColor" format="color" />
<attr name="inputHint" format="string" />
<attr name="inputDelImageRes" format="reference" />
<attr name="inputDelImageHidden" format="boolean" />
<attr name="inputPreHintHidden" format="boolean" />
</declare-styleable>
 * */
class LoginUserNameInput : RelativeLayout, BaseFormAction,
    BaseEditAction {

    lateinit var mViewBinding: ViewLoginUserNameInputBinding
    private lateinit var vRootView: View

    private var inputTextColor: Int = 0
    private var inputHintColor: Int = 0
    private var inputTitle: String? = null
    private var inputText: String? = null
    private var inputHint: String? = null
    private var inputPreHintImageRes: Int = 0
    private var inputDelImageRes: Int = 0
    private var inputDelImageHidden: Boolean = false
    private var inputPreHintHidden: Boolean = false
    private var inputIsTitleBold: Boolean = true
    private var inputTitleSize: Float = 0F

    private var mSupportFragmentManager: FragmentManager? = null

    private var mTempInputValue: String = ""
    private var mOnActionClickListener: (Int) -> Unit = {}
    private var mOnTextChangedListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.LoginUserNameInput)
                inputTextColor = array.getColor(
                    R.styleable.LoginUserNameInput_inputTextColor,
                    ContextCompat.getColor(cxt, R.color.text_title)
                )
                inputText =
                    array.getString(R.styleable.LoginUserNameInput_inputText)

                inputTitle =
                    array.getString(R.styleable.LoginUserNameInput_inputTitle)

                inputHintColor = array.getColor(
                    R.styleable.LoginUserNameInput_inputHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                inputHint =
                    array.getString(R.styleable.LoginUserNameInput_inputHint)

                inputDelImageRes =
                    array.getResourceId(
                        R.styleable.LoginUserNameInput_inputDelImageRes,
                        R.drawable.icon_close
                    )
                inputDelImageHidden = array.getBoolean(
                    R.styleable.LoginUserNameInput_inputDelImageHidden,
                    true
                )
                inputPreHintImageRes =
                    array.getResourceId(
                        R.styleable.LoginUserNameInput_inputPreHintImageRes,
                        R.drawable.icon_login_user
                    )
                inputIsTitleBold = array.getBoolean(
                    R.styleable.LoginUserNameInput_inputIsTitleBold,
                    true
                )

                inputTitleSize = array.getDimension(
                    R.styleable.LoginUserNameInput_inputTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_12
                    ).toFloat()
                )

                inputPreHintHidden = array.getBoolean(
                    R.styleable.LoginUserNameInput_inputPreHintHidden,
                    false
                )

                array.recycle()
            }
        }
        context?.let {
            vRootView =
                View.inflate(it, R.layout.view_login_user_name_input, this)
            mViewBinding =
                ViewLoginUserNameInputBinding.bind(vRootView)
            initSubviews()
        }
    }

    override fun initSubviews() {
        try {
            mViewBinding.textLoginUserNameTitle.text = inputTitle
            mViewBinding.textLoginUserNameTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                inputTitleSize
            )
            if (inputIsTitleBold) {
                mViewBinding.textLoginUserNameTitle.addBoldStyle()
            } else {
                mViewBinding.textLoginUserNameTitle.addNormalStyle()
            }

            mViewBinding.editLoginUserName.setText(inputText)
            mViewBinding.editLoginUserName.setTextColor(inputTextColor)

            mViewBinding.editLoginUserName.hint = (inputHint)
            mViewBinding.editLoginUserName.setHintTextColor(inputHintColor)

            mViewBinding.imageLoginUserNameDel.setImageResource(inputDelImageRes)

            mViewBinding.llLoginUserNameDelBg.setOnClickListener {
                mOnActionClickListener.invoke(0)
            }

            mViewBinding.imageLoginUserNameDel.setOnClickListener {
                mOnActionClickListener.invoke(0)
            }

            if (inputPreHintHidden) {
                mViewBinding.imageLoginUserNamePreHint.visibility = GONE
            } else {
                mViewBinding.imageLoginUserNamePreHint.visibility = VISIBLE
            }


            mViewBinding.editLoginUserName.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isCompleted()
                    val gContent = getContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mTempInputValue,
                                false
                            )
                        ) {
                            try {
                                mTempInputValue = gContent
                                recordInputEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                    val tempContent = getContent()
                    if (tempContent.isNotBlank()) {
                        if (inputDelImageHidden) {
                            mViewBinding.llLoginUserNameDelBg.visibility = GONE
                        } else {
                            mViewBinding.llLoginUserNameDelBg.visibility =
                                VISIBLE
                        }

                    } else {
                        mViewBinding.llLoginUserNameDelBg.visibility = GONE
                    }
                }
            }
            mViewBinding.editLoginUserName.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getContent()
                    if (tempContent.isNotBlank()) {
                        if (inputDelImageHidden) {
                            mViewBinding.llLoginUserNameDelBg.visibility = GONE
                        } else {
                            mViewBinding.llLoginUserNameDelBg.visibility =
                                VISIBLE
                        }
                    } else {
                        mViewBinding.llLoginUserNameDelBg.visibility = GONE
                    }
                    //回调
                    mOnTextChangedListener.invoke(
                        tempContent
                    )
                }
            })

            mViewBinding.llLoginUserNameDelBg.setOnClickListener {
                mViewBinding.editLoginUserName.setText("")
            }
            mViewBinding.imageLoginUserNameDel.setOnClickListener {
                mViewBinding.editLoginUserName.setText("")
            }

            //增加星号显示
            mViewBinding.textLoginUserNameTitle.addHighlightStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setContent(content: String) {
        mViewBinding.editLoginUserName.setText(content)
    }

    fun getContent(): String {
        return mViewBinding.editLoginUserName.text.toString().trim()
    }

    fun isCompleted(): Boolean {
        val gcontent = getContent()
        if (gcontent.isBlank()) {
            mViewBinding.rlLoginUserNameBg.setBackgroundResource(R.drawable.form_input_error)
            mViewBinding.textLoginUserNameErrTip.visibility = VISIBLE
            return false
        }

        mViewBinding.textLoginUserNameErrTip.visibility = GONE
        mViewBinding.rlLoginUserNameBg.setBackgroundResource(R.drawable.form_input)
        return true
    }

    fun isCompletedSlient(): Boolean {
        val gcontent = getContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toBeFocusPointAndShowInputKeyboard() {
        try {
            mViewBinding.editLoginUserName.isFocusable = true
            mViewBinding.editLoginUserName.isFocusableInTouchMode = true
            mViewBinding.editLoginUserName.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(
                            mViewBinding.editLoginUserName,
                            0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toBeFocusPoint() {
        try {
            mViewBinding.editLoginUserName.isFocusable = true
            mViewBinding.editLoginUserName.isFocusableInTouchMode = true
            mViewBinding.editLoginUserName.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setInputHint(hint: String) {
        val hintFormat = hint.toPhoneNumberInputHint()
        mViewBinding.editLoginUserName.hint = hintFormat
    }

    override fun setFragmentManager(manager: FragmentManager) {
        mSupportFragmentManager = manager
    }

    override fun setOnActionClickListener(listener: (Int) -> Unit) {
        mOnActionClickListener = listener
    }

    override fun setOnTextChangedListener(listener: (String) -> Unit) {
        mOnTextChangedListener = listener
    }

    override fun setTitle(title: String) {

    }

    override fun setDetail(detail: String) {

    }

    override fun setHint(hint: String) {
        setInputHint(hint)
    }

    override fun setDetailColor(detailColor: Int) {

    }

    override fun setTitleColor(titleColor: Int) {

    }

    fun clean() {
        mViewBinding.editLoginUserName.setText(null)
    }

}